Page({
  data: {
    record: {},
    total: [],
    correctAnswer: '',
    select: '',
    currentIndex: 0, 
    Ai_content: '', 
    modalName: null,
    loading: true ,
    envVersion:'',
  },

  onLoad(options) {
    const id = options._id;
    const app = getApp();
    const envVersion = app.globalData.envVersion;
    this.setData({
      envVersion:envVersion
    })
    console.log('传过来的id', id);
    this.getDtails(id);
  },

  getDtails: function (id) {
    const db = wx.cloud.database();
    db.collection('answer_record').doc(id).get().then(res => {
      if (res.data.answers && res.data.answers.length > 0) {
        console.log('数据', res.data.answers);
        this.setData({
          total: res.data.answers,
          record: res.data.answers[0], // 初始时设置为第一组内容
          correctAnswer: res.data.answers[0].correctAnswer,
          select: res.data.answers[0].selectedOption
        });
      } else {
        console.log('No answers found');
      }
    }).catch(err => {
      console.error('Failed to get details', err);
    });
  },

  nextQuestion: function () {
    if (this.data.currentIndex < this.data.total.length - 1) {
      const nextIndex = this.data.currentIndex + 1; 
      const nextRecord = this.data.total[nextIndex]; 

      // 更新数据
      this.setData({
        record: nextRecord,
        correctAnswer: nextRecord.correctAnswer,
        select: nextRecord.selectedOption,
        currentIndex: nextIndex 
      });
    } else {
      wx.showToast({
        title: '已到最后一题',
        icon: 'none'
      });
    }
  },

  previousQuestion: function () {
    if (this.data.currentIndex > 0) {
      const previousIndex = this.data.currentIndex - 1; 
      const previousRecord = this.data.total[previousIndex]; 

      
      this.setData({
        record: previousRecord,
        correctAnswer: previousRecord.correctAnswer,
        select: previousRecord.selectedOption,
        currentIndex: previousIndex 
      });
    } else {
      wx.showToast({
        title: '这是第一题',
        icon: 'none'
      });
    }
  },

  hideModal(e) {
    this.setData({
      modalName: null
    });
  },

  getAi: async function (e) {
    this.setData({
      modalName: 'DialogModal1',
      Ai_content: '', 
      loading:true 
    });
    const model = wx.cloud.extend.AI.createModel("deepseek");
    const userInput = "为什么" + this.data.record.question + "的答案是" + this.data.correctAnswer;
    const res = await model.streamText({
      data: {
        model: "deepseek-v3", 
        messages: [
          { role: "user", content: userInput },
        ],
      },
    });
    let response = '';
    for await (let str of res.textStream) {
      console.log(userInput)
      response += str;
      this.setData({
        Ai_content: response,
        loading:false  
      });
    }


  }
});
